<template>
  <el-input
    v-bind="$attrs"
    v-model="inputValue"
    type="textarea"
    :autosize="{ minRows: 1, maxRows: 3 }"
    :placeholder="placeholder"
    clearable
    @blur="blurInput"
    @keyup="handleKeyUp"
  >
  </el-input>
</template>

<script name="MultiInput" setup>
import { reactive, toRefs } from "vue";

const props = defineProps({
  modelValue: {
    type: [Array, String],
    default: () => [],
  },
  placeholder: {
    type: String,
    default: "",
  },
});

const emits = defineEmits(["update:modelValue"]);
const inputValue = ref("");

watch(
  () => props.modelValue,
  (val) => {
    if (!val.length || !val) {
      inputValue.value = "";
    } else {
      inputValue.value = val.join("\n");
    }
  }
);

const blurInput = () => {
  const val = inputValue.value ? inputValue.value.split("\n").filter((d) => d) : [];
  emits("update:modelValue", val);
};

onMounted(() => {
  // 在组件内部添加键盘事件监听器
  document.addEventListener("keyup", handleKeyUp);
});

onBeforeUnmount(() => {
  // 在组件销毁前移除键盘事件监听器
  document.removeEventListener("keyup", handleKeyUp);
});

const handleKeyUp = (event) => {
  if (event.keyCode === 13 || event.key === "Enter") {
    event.stopPropagation(); // 事件冒泡
  }
};
</script>

<style lang="scss"></style>
